using System;
using System.Windows;
using Autodesk.Revit.UI;
using RevitForge.Views;
using RevitForge.ViewModels;

namespace RevitForge.Services
{
    public class ScriptBotDockablePaneProvider : IDockablePaneProvider
    {
        private ScriptBotView _paneView;
        private readonly ExternalEvent _scriptExecuteEvent;
        public static readonly DockablePaneId PaneId = new DockablePaneId(new Guid("B8F489E7-0C5D-4DB1-8B3C-4E0DE0E3E217"));

        public ScriptBotDockablePaneProvider(ExternalEvent scriptExecuteEvent)
        {
            _scriptExecuteEvent = scriptExecuteEvent;
        }

        public static void Register(UIControlledApplication application)
        {
            try
            {
                // 注册可停靠窗格
                if (!DockablePane.PaneIsRegistered(PaneId))
                {
                    application.RegisterDockablePane(PaneId, "ScriptBot", new ScriptBotDockablePaneProvider(null));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"注册可停靠窗口失败: {ex.Message}");
            }
        }

        public static void ShowPane(UIApplication uiapp, bool? show = null)
        {
            try
            {
                DockablePane dp = uiapp.GetDockablePane(PaneId);
                if (dp != null)
                {
                    // show为null时切换状态，否则设置为指定状态
                    bool shouldShow = show ?? !dp.IsShown();
                    if (shouldShow) dp.Show();
                    else dp.Hide();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作可停靠窗口失败: {ex.Message}");
            }
        }

        public void SetupDockablePane(DockablePaneProviderData data)
        {
            _paneView = new ScriptBotView(_scriptExecuteEvent);

            data.FrameworkElement = _paneView;
            data.InitialState = new DockablePaneState
            {
                DockPosition = DockPosition.Tabbed,
                TabBehind = DockablePanes.BuiltInDockablePanes.ProjectBrowser
            };
        }
    }
}